package controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import application.AlertDialog;
import application.ProgressFrom;
import bean.Customer;
import bean.GoodDetails;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import service.FpService;
import task.ExcelTask;
import task.XmlTask;
import util.ExcelUtil;
import util.FpUtil;
import util.PropertyUtil;
import util.khxxUtil;

public class FpMainController implements Initializable {

	@FXML
	private Label date;
	
	@FXML
	private Button kjfp;
	
	@FXML
	private Button del;
	
    @FXML
    private MenuItem openFile;
    
    @FXML
    private MenuItem closeFile;
    
    @FXML
    private MenuItem export;
    
    @FXML
    private MenuItem exit;
    
    @FXML
    private TableColumn<Customer, Boolean> checkAllCol;
    
    @FXML
    private TableColumn<Customer, String> billCodeCol;
    
    @FXML
    private TableColumn<Customer, String> shCol;
    
    @FXML
    private TableColumn<Customer, String> statusCol;

    @FXML
    private TableColumn<Customer, String> dzdhCol;
    
    @FXML
    private TableColumn<Customer, String> yhzhCol;
    
    @FXML
    private TableColumn<Customer, String> nameCol;
    
    @FXML
    private TableColumn<Customer, String> sumAmountCol;
    
    @FXML
    private TableColumn<Customer, String> disCountCol;
    
    @FXML
    private TableView<Customer> tv_customer;
    
    @FXML
    private TableColumn<GoodDetails, String> goodCodeCol;
    
    @FXML
    private TableColumn<GoodDetails, String> goodNameCol;
    
    @FXML
    private TableColumn<GoodDetails, String> standardCol;
    
    @FXML
    private TableColumn<GoodDetails, String> dwCol;
    
    @FXML
    private TableColumn<GoodDetails, String> priceCol;
    
    @FXML
    private TableColumn<GoodDetails, String> numCol;
    
    @FXML
    private TableColumn<GoodDetails, String> amountCol;
    
    @FXML
    private TableView<GoodDetails> tv_goodDetail;
    
    @FXML
    private TextField fhr;
    
    @FXML
    private TextField skr;
    
    @FXML
    private TextField spbm;
    
    @FXML
    private TextField limit;
    
    @FXML
    private TextField searchFeild;
    
    @FXML
    private Text sumAmount;
    
    @FXML
    private Text sumDiscount;
    
    @FXML
    private CheckBox checkAll;
    
    @FXML
    private Font x3;

    @FXML
    private Color x4;
    
    //文件转换后的map
    private static Map<String,Customer> map = new HashMap<String,Customer>();
    //勾选中的map
    private static Map<String,Customer> selectMap = new HashMap<String,Customer>();
    //tv中的list
    private static List<Customer> userList = new ArrayList<Customer>();
    
    /**
     * 设置限额
     * @param event
     */
    @FXML
    void limitChangeAction(KeyEvent event){
    	if(event.getCode() == KeyCode.ENTER){
    		if(!limit.getText().equals("")){
    			PropertyUtil.writeProperties("limit", limit.getText());
    		}else{
    			PropertyUtil.writeProperties("limit", "99999.99");
    		}
    	}
    }
    
    /**
     * 读取开票结果
     * @param event
     */
    @FXML
    void readResultAction(ActionEvent event){
    	if(selectMap.isEmpty()){
    		AlertDialog.informationDialog("提示", "请选择至少一张单据", ((Node) event.getSource()).getScene().getWindow());
    		return;
    	}
		List<Customer> temp = new ArrayList<Customer>();
		for (String name : selectMap.keySet()) {
			Customer customer = selectMap.get(name);
			String result = FpService.FpResult(customer.getBillCode());
			String code = "";
			if(result.split(",").length != 1){
				code = result.split(",")[1].split(":")[1];
			}else{
				code = "0";
			}
			if(code.equals("0")){
				customer.setStatus(result);
				customer.setIsSelected(false);
			}else{
				temp.add(customer);
			}
		}
		//清空
		selectMap = new HashMap<String,Customer>();
		
		checkAll.setSelected(false);
		
		userList.removeAll(temp);
		
		configCustomerTable(userList);
		
		tv_goodDetail.setItems(null);
		
		//在读取结果前不允许其他操作
		kjfp.setDisable(false);
		
		del.setDisable(false);
		
		//将生成成功的数据写入db文件
		
		FpUtil.writeData(temp);
		
		//写入temp.db
		FpUtil.writeDataTemp(userList);
    }
    
    /**
     * 开具发票
     * @param event
     */
    @FXML
    void kjfpAction(ActionEvent event){
    	if(selectMap.isEmpty()){
    		AlertDialog.informationDialog("提示", "请选择至少一张单据", kjfp.getScene().getWindow());
    		return;
    	}
    	if(!AlertDialog.confirmDialog("确定开票？", "确定生成"+selectMap.size()+"条数据")){
    		return;
    	}
    	
    	if(spbm.getText().equals("")){
    		spbm.setText("107020602");
    	}
    	PropertyUtil.writeProperties("skr", skr.getText());
    	PropertyUtil.writeProperties("fhr", fhr.getText());
    	//生成xml
    	XmlTask xmlTask = new XmlTask(selectMap,skr.getText(),fhr.getText(),spbm.getText());
    	xmlTask.valueProperty().addListener(new XmlTaskListener());
		
		ProgressFrom progressFrom = new ProgressFrom(xmlTask,openFile.getParentPopup().getOwnerWindow());
		progressFrom.activateProgressBar();
    }
    
    class XmlTaskListener implements ChangeListener<List<Customer>> {

		@Override
		public void changed(ObservableValue<? extends List<Customer>> observable, List<Customer> oldValue,
				List<Customer> newValue) {
			
			//checkAll.setSelected(false);
			
			//在读取结果前不允许其他操作
			kjfp.setDisable(true);
			
			del.setDisable(true);
			
			AlertDialog.informationDialog("生成成功"
					, "成功生成"+newValue.size()+"条记录，待开票完成后读取发票结果", kjfp.getScene().getWindow());
			
		}
    }
    
    /**
     * 刷新，重新加载税号
     * @param event
     */
    @FXML
    void refreshAction(ActionEvent event){
    	List<HashMap<String, String>> khxx = khxxUtil.getMsg();
    	for (Customer customer : userList) {
			customer.setSh(ExcelUtil.updateSh(customer.getName(), khxx));
		}
    	configCustomerTable(userList);
    }
    
    
    /**
     * 搜索
     * @param event
     */
    @FXML
    void searchAction(ActionEvent event){
    	String keyword = searchFeild.getText();
    	List<Customer> cusList = new ArrayList<Customer>();
    	if(keyword.equals("")){
    		for (String billCode : map.keySet()) {
				Customer customer = map.get(billCode);
				cusList.add(customer);
			}
    	}else{
    		for (Customer customer : userList) {
				if(customer.getName().indexOf(keyword)!=-1){
					cusList.add(customer);
				}
			}
    	}
    	configCustomerTable(cusList);
    }
    
    /**
     * 导出Excel
     * @param event
     */
    @FXML
    void exportAction(ActionEvent event){
    	if(selectMap.isEmpty()){
    		AlertDialog.informationDialog("提示", "请选择至少一张单据", export.getParentPopup().getOwnerWindow());
    		return;
    	}
    	if(!AlertDialog.confirmDialog("确定导出？", "确定导出"+selectMap.size()+"条数据")){
    		return;
    	}
    	Boolean flag = ExcelUtil.exportData(selectMap);
    	if(flag){
    		AlertDialog.informationDialog("提示", "导出成功", export.getParentPopup().getOwnerWindow());
    	}else{
    		AlertDialog.informationDialog("提示", "导出失败", export.getParentPopup().getOwnerWindow());
    	}
    	
    }
    
    /**
     * openFile-->打开xls文件操作
     * @param event
     */
    @FXML
    void openFileAction(ActionEvent event) {
		//文件选择框
		FileChooser fileChooser = new FileChooser();
		//文件筛选
		List<String> filter = new ArrayList<String>();
		filter.add("*.xls");
		filter.add("*.xlsx");
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("EXCEL files (*.xls,*.xlsx)", filter);
        fileChooser.getExtensionFilters().add(extFilter);
        
        //获取上次设置的excel路径
        String excelPath = PropertyUtil.getKeyValue("excelPath");
        if(!excelPath.equals("")&&new File(excelPath).exists()){
        	fileChooser.setInitialDirectory(new File(excelPath));
        }
        File file = fileChooser.showOpenDialog(openFile.getParentPopup().getOwnerWindow());
		//路径回显
        if(file!=null){
        	//将excel文档设置路径存入config文件中
        	PropertyUtil.writeProperties("excelPath", file.getParent());
        	//创建一个与当前文件相同文件名的db文件
        	FpUtil.createFileByName();
        	
        	ExcelTask excelTask = new ExcelTask(file);
        	
        	
        	excelTask.valueProperty().addListener(new ExcelTaskListener());
    		ProgressFrom progressFrom = new ProgressFrom(excelTask,openFile.getParentPopup().getOwnerWindow());
    		progressFrom.activateProgressBar();
        	
        }
    }
    
    class ExcelTaskListener implements ChangeListener<List<Customer>> {

    	@Override
    	public void changed(ObservableValue<? extends List<Customer>> observable, List<Customer> oldValue,
			List<Customer> newValue) {
			List<GoodDetails> fsDetail = new ArrayList<GoodDetails>();
			List<GoodDetails> zsDetail = new ArrayList<GoodDetails>();
			List<Customer> result = new ArrayList<Customer>();
			//合并单据
			newValue = FpUtil.merge(newValue);
			//检查是否存在促销赠送商品
			BigDecimal sumAmountTemp = new BigDecimal(0);
			BigDecimal limit = new BigDecimal(PropertyUtil.getKeyValue("limit"));
			for (Customer customer : newValue) {
				//如果存在促销商品
				if(customer.getIsPromotion()){
					customer = FpUtil.checkPromotion(customer);
					if(customer == null){
						continue;
					}
				}
				for (int i = 0; i < customer.getGoodDetails().size(); i++) {
					GoodDetails goodDetails = customer.getGoodDetails().get(i);
					
					if(new BigDecimal(goodDetails.getAmount()).compareTo(new BigDecimal(0))==-1){
						fsDetail.add(goodDetails);
					}else{
						BigDecimal amount = new BigDecimal(goodDetails.getAmount());
						//判断单行超限
						if(amount.compareTo(limit) == 1){
							//单行超限拆分
							List<GoodDetails> templist = FpService.splitLine(goodDetails,limit);
							//拆分后所有添加到正数商品行
							zsDetail.addAll(templist);
						}else{
							zsDetail.add(goodDetails);
						}
						sumAmountTemp = sumAmountTemp.add(amount);
					}
				}
				
				if((new BigDecimal(customer.getSumAmount()).subtract(new BigDecimal(customer.getDisCount())))
						.compareTo(new BigDecimal(PropertyUtil.getKeyValue("limit")))==1){
					//总金额超限
					List<List<GoodDetails>> tempSplitTotal = FpService.splitTotal(zsDetail,limit);
					for (int i = 0; i < tempSplitTotal.size(); i++) {
						Customer cloneCus = customer.clone();
						//复制的不参与折扣
						String billCode = cloneCus.getBillCode()+"_split"+(i+1);
						if(i!=0){
							cloneCus.setDisCount("0");
						}
						cloneCus.setIsRed(true);
						cloneCus.setBillCode(billCode);
						cloneCus.setSph(tempSplitTotal.get(i).size()+"");
						String tempSum = FpService.getSumAmount(tempSplitTotal.get(i));
						cloneCus.setSumAmount(tempSum);
						cloneCus.setGoodDetails(tempSplitTotal.get(i));
						map.put(billCode, cloneCus);
						result.add(cloneCus);
					}
				}else{
					customer.setSumAmount(sumAmountTemp.toString());
					customer.setGoodDetails(zsDetail);
					customer.setSph(zsDetail.size()+"");
					map.put(customer.getBillCode(), customer);
					result.add(customer);
				}
				zsDetail = new ArrayList<GoodDetails>();
				sumAmountTemp = new BigDecimal(0);
			}
			
			//消除重复数据
			result = FpService.clearRepeat(result);
			//计算折扣金额
			for (Customer cus : result) {
				BigDecimal disTotal = new BigDecimal(cus.getDisCount());
				if (disTotal.compareTo(new BigDecimal(0)) != 0 ) {
					System.out.println(cus.getName()+"----"+disTotal);
				}
				if(disTotal.compareTo(new BigDecimal(cus.getSumAmount())) == 1){
					disTotal =  new BigDecimal(0.00);
				}
				cus.setDisCount(disTotal.toString());
			}
			
			if(result.size()!=0){
				userList.addAll(result);
			}
			
			
			if(fsDetail.size()!=0){//存在负数单据
				String path = ExcelUtil.writeRedExcel(fsDetail);
				if(path.equals("") || path == null ){
					AlertDialog.informationDialog("存在冲红单据", "生成冲红数据失败", openFile.getParentPopup().getOwnerWindow());
				}else{
					AlertDialog.informationDialog("存在冲红单据", "生成冲红数据成功，路径："+path,openFile.getParentPopup().getOwnerWindow());
				}
			}
			//初始化table
			configCustomerTable(userList);
			
			//写入temp.db
			FpUtil.writeDataTemp(userList);
    	}

    }
    
    /**
     * closeFile --> 关闭文件操作
     * @param event
     */
    @FXML
    void closeFileAction(ActionEvent event) {
    	return;
    	/**if(kjfp.isDisable()){
    		if(!AlertDialog.confirmDialog("警告", "存在未读取结果发票，关闭文件将会造成数据丢失，确定关闭当前文件？")){
    			return;
    		}
    	}
    	tv_customer.setItems(null);
    	tv_goodDetail.setItems(null);
    	userList = new ArrayList<Customer>();
    	FpUtil.writeDataTemp(userList);
    	map = new HashMap<String,Customer>();**/
    }
    
    /**
     * exit-->退出程序
     * @param event
     */
    @FXML
    void exitAction(ActionEvent event) {
    	if(kjfp.isDisable()){
    		if(!AlertDialog.confirmDialog("警告", "存在未读取结果发票，关闭文件将会造成数据丢失，确定关闭当前文件？")){
    			return;
    		}
    	}
    	if(AlertDialog.confirmDialog("退出", "确定退出程序？")){
    		tv_customer.setItems(null);
    		tv_goodDetail.setItems(null);
    		userList = new ArrayList<Customer>();
    		map = new HashMap<String,Customer>();
    		System.exit(0);
    	}else{
    		return;
    	}
    }
    
    
    /**
     * del-->删除
     * @param event
     */
    @FXML
    void delAction(ActionEvent event) {
    	if(AlertDialog.confirmDialog("删除", "确定删除"+selectMap.size()+"条记录?")){
    		List<Customer> temp = new ArrayList<Customer>();
    		for (String billCode : selectMap.keySet()) {
    			Customer customer = selectMap.get(billCode);
				temp.add(customer);
				map.remove(billCode);
				sumAmount.setText(new BigDecimal(sumAmount.getText()).subtract(new BigDecimal(customer.getSumAmount())).toString());
				sumDiscount.setText(new BigDecimal(sumDiscount.getText())
						.subtract(new BigDecimal(customer.getDisCount()==null?"0.00":customer.getDisCount())).toString());
			}
    		userList.removeAll(temp);
    		//清空勾选
    		selectMap = new HashMap<String,Customer>();
    		
    		checkAll.setSelected(false);
    		
    		configCustomerTable(userList);
    		
    		//将当期文件写入temp.db
    		FpUtil.writeDataTemp(userList);
    		
    		tv_goodDetail.setItems(null);
    	}else{
    		return;
    	}
    }
    
    /**
     * edit-->客户信息维护
     * @param event
     */
    @FXML
    void customerAction(ActionEvent event) {
    	Stage stage = new Stage();
        Parent root;
		try {
			root = FXMLLoader.load(getClass().getClassLoader().getResource("view/CustomerView.fxml"));
			stage.setScene(new Scene(root));
	        stage.setTitle("客户信息维护");
	        stage.initModality(Modality.WINDOW_MODAL);
	        stage.setResizable(false);
	        stage.getIcons().add(new Image("/image/change.png"));
	        stage.initOwner(((MenuItem)event.getSource()).getParentPopup().getOwnerWindow());
	        stage.show();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 打开Excel导入设置格式
     * @param event
     */
/*    @FXML
    void installExcelAction(ActionEvent event){
    	Stage stage = new Stage();
        Parent root;
		try {
			root = FXMLLoader.load(getClass().getClassLoader().getResource("view/CustomerView.fxml"));
			stage.setScene(new Scene(root));
	        stage.setTitle("Excel格式设置");
	        stage.initModality(Modality.WINDOW_MODAL);
	        stage.setResizable(false);
	        stage.getIcons().add(new Image("/image/change.png"));
	        *//**stage.initOwner(
	            (openFile.getParentPopup().getOwnerWindow()));**//*
	        stage.initOwner(((MenuItem)event.getSource()).getParentPopup().getOwnerWindow());
	        stage.show();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }*/
    
    /**
     * 全选checkbox事件监听
     * @param event
     */
    @FXML
    void selectAllAction(ActionEvent event){
    	CheckBox checkBox = (CheckBox) event.getSource();
    	Boolean flag = checkBox.selectedProperty().getValue();

    	ObservableList<Customer> list = tv_customer.getItems();
    	selectMap = new HashMap<String,Customer>();
    	BigDecimal sumAmountTemp = new BigDecimal(0);
		BigDecimal sumDiscountTemp = new BigDecimal(0);
    	for (Customer customer : list) {
    		customer.setIsSelected(flag);
			if(flag){
				selectMap.put(customer.getBillCode(),customer);
				sumAmountTemp = sumAmountTemp.add(new BigDecimal(customer.getSumAmount())).setScale(2,BigDecimal.ROUND_HALF_UP);
				sumDiscountTemp = sumDiscountTemp.add(new BigDecimal(customer.getDisCount()==null?"0":customer.getDisCount())).setScale(2,BigDecimal.ROUND_HALF_UP);
			}else{
				selectMap.remove(customer.getBillCode());
				sumAmountTemp = new BigDecimal(0).setScale(2,BigDecimal.ROUND_HALF_UP);
				sumDiscountTemp = new BigDecimal(0).setScale(2,BigDecimal.ROUND_HALF_UP);
			}
		}    	
    	sumAmount.setText(sumAmountTemp.toString());
    	sumDiscount.setText(sumDiscountTemp.toString());
    	tv_customer.setItems(list);
    }
    
    /**
     * 初始化商品列
     * @param cusList
     * @return
     */
	public void configCustomerTable(List<Customer> cusList) {
		billCodeCol.setCellValueFactory(new PropertyValueFactory<>("billCode"));
		nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
		disCountCol.setCellValueFactory(new PropertyValueFactory<>("disCount"));
		shCol.setCellValueFactory(new PropertyValueFactory<>("sh"));
		dzdhCol.setCellValueFactory(new PropertyValueFactory<>("dzdh"));
		yhzhCol.setCellValueFactory(new PropertyValueFactory<>("yhzh"));
		billCodeCol.setCellFactory(new Callback<TableColumn<Customer,String>, TableCell<Customer,String>>() {
			@Override
			public TableCell<Customer, String> call(TableColumn<Customer, String> param) {
				return new TableCell<Customer,String>() {
					
					public void updateItem(String item,boolean empty){
						super.updateItem(item, empty);
						if(!isEmpty()){
							Customer customer = (Customer) this.getTableRow().getTableView().getItems().get(getIndex());
							//if(customer.getIsRed()){
							if (customer.getBillCode().indexOf("_split")!=-1) {
								this.setTextFill(Color.RED);
							}else{
								this.setTextFill(Color.BLACK);
							}
							setText(item); 
						}
					}
				};
			}
		});
		
		statusCol.setCellValueFactory(new PropertyValueFactory<>("status"));
		sumAmountCol.setCellValueFactory(new PropertyValueFactory<>("sumAmount"));

		checkAllCol.setCellValueFactory(new PropertyValueFactory<Customer, Boolean>("isSelected"));
		checkAllCol.setCellFactory(column -> new TableCell<Customer, Boolean>(){
	        public void updateItem(Boolean check, boolean empty) {
	            super.updateItem(check, empty);
	            if (check == null || empty) {
	                setGraphic(null);
	            } else {
	                CheckBox checkBox = new CheckBox();
	                setGraphic(checkBox);
	                setAlignment(Pos.CENTER);
	                Customer customer = column.getTableView().getItems().get(getIndex());
	                String billCode = customer.getBillCode();
	                checkBox.setSelected(customer.getIsSelected());
	                checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
						public void changed(ObservableValue<? extends Boolean> ov,
								Boolean old_val, Boolean new_val) {
							checkBox.setAlignment(Pos.CENTER);
							checkBox.setSelected(new_val);
							//customer.setIsSelected(new_val);
							//判断当前状态是否为选中状态
							if(new_val){
								//选中
								selectMap.put(billCode, customer);
							}else{
								//没选中
								selectMap.remove(billCode);
							}
							BigDecimal sumAmountTemp = new BigDecimal(0).setScale(2);
							BigDecimal sumDiscountTemp = new BigDecimal(0).setScale(2);
							for (String key : selectMap.keySet()) {
								Customer cus = selectMap.get(key);
								sumAmountTemp = sumAmountTemp.add(new BigDecimal(cus.getSumAmount())).setScale(2,BigDecimal.ROUND_HALF_UP);
								sumDiscountTemp = sumDiscountTemp.add(new BigDecimal(cus.getDisCount()==null?"0.00":cus.getDisCount())).setScale(2,BigDecimal.ROUND_HALF_UP);
							}
							sumAmount.setText(sumAmountTemp.toString());
							sumDiscount.setText(sumDiscountTemp.toString());
						}
					});
	            }
	        }
	    });
		
		
		//javaFx放置数据集合
		ObservableList<Customer> list = FXCollections.observableArrayList();
		
		for (Customer customer : cusList) {
			if(!"0".equals(customer.getDisCount())){
				customer = FpService.updateByDiscount(customer.getDisCount(),customer);
			}
			list.add(customer);
		}

		tv_customer.setItems(list);
	}
	
	/**
	 * 初始化商品窗口
	 * @param customer
	 */
	protected void configGoodTable(Customer customer) {
		goodCodeCol.setCellValueFactory(new PropertyValueFactory<GoodDetails, String>("goodCode"));
		goodNameCol.setCellValueFactory(new PropertyValueFactory<GoodDetails, String>("goodName"));
		standardCol.setCellValueFactory(new PropertyValueFactory<GoodDetails, String>("standard"));
		dwCol.setCellValueFactory(new PropertyValueFactory<GoodDetails, String>("dw"));
		priceCol.setCellValueFactory(new PropertyValueFactory<GoodDetails, String>("price"));
		numCol.setCellValueFactory(new PropertyValueFactory<GoodDetails, String>("num"));
		amountCol.setCellValueFactory(new PropertyValueFactory<GoodDetails, String>("amount"));
		
		//javaFx放置数据集合
		ObservableList<GoodDetails> list = FXCollections.observableArrayList();
		for (GoodDetails goodDetails : customer.getGoodDetails()) {
			list.add(goodDetails);
		}
		
		tv_goodDetail.setItems(list);
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		
		//设置tv_user可编辑
		tv_customer.setEditable(true);
		nameCol.setCellFactory(TextFieldTableCell.forTableColumn());
		nameCol.setOnEditCommit(  
	          (CellEditEvent<Customer, String> t) -> {  
	        	  String gfName = t.getNewValue();
	        	  Customer customer = t.getTableView().getItems().get(t.getTablePosition().getRow());
	        	  customer.setName(gfName);
	        	  //重新加载tv_goodDetail
	        	  configGoodTable(customer);
	        	  map.put(customer.getBillCode(), customer);
	        	  //保存到temp.db中
	        	  FpUtil.writeDataTemp(map);
		});
		
		dzdhCol.setCellFactory(TextFieldTableCell.forTableColumn());
		dzdhCol.setOnEditCommit(  
	          (CellEditEvent<Customer, String> t) -> {  
	        	  String dzdh = t.getNewValue();
	        	  Customer customer = t.getTableView().getItems().get(t.getTablePosition().getRow());
	        	  customer.setDzdh(dzdh);
	        	  //重新加载tv_goodDetail
	        	  configGoodTable(customer);
	        	  map.put(customer.getBillCode(), customer);
	        	  //保存到temp.db中
	        	  FpUtil.writeDataTemp(map);
		});
		
		yhzhCol.setCellFactory(TextFieldTableCell.forTableColumn());
		yhzhCol.setOnEditCommit(  
	          (CellEditEvent<Customer, String> t) -> {  
	        	  String yhzh = t.getNewValue();
	        	  Customer customer = t.getTableView().getItems().get(t.getTablePosition().getRow());
	        	  customer.setYhzh(yhzh);
	        	  //重新加载tv_goodDetail
	        	  configGoodTable(customer);
	        	  map.put(customer.getBillCode(), customer);
	        	  //保存到temp.db中
	        	  FpUtil.writeDataTemp(map);
		});
		
		
		disCountCol.setCellFactory(TextFieldTableCell.forTableColumn());
		disCountCol.setOnEditCommit(  
	          (CellEditEvent<Customer, String> t) -> {  
	        	  String discount = t.getNewValue();
	        	  Customer customer = t.getTableView().getItems().get(t.getTablePosition().getRow());
	        	  customer.setDisCount(discount);
	        	  customer = FpService.updateByDiscount(discount,customer);
	        	  //重新加载tv_goodDetail
	        	  configGoodTable(customer);
	        	  map.put(customer.getBillCode(), customer);
	        	  //保存到temp.db中
	        	  FpUtil.writeDataTemp(map);
	    });
		shCol.setCellFactory(TextFieldTableCell.forTableColumn());
		shCol.setOnEditCommit(  
		          (CellEditEvent<Customer, String> t) -> {  
		        	  String sh = t.getNewValue();
		        	  Customer customer = t.getTableView().getItems().get(t.getTablePosition().getRow());
		        	  customer.setSh(sh);
		        	  //更新khxx.db中的税号
		        	  FpService.updateSh(customer,t.getTablePosition().getRow());
		        	  //重新加载tv_goodDetail
		        	  configGoodTable(customer);
		        	  map.put(customer.getBillCode(), customer);
		        	  for (String key : map.keySet()) {
		        		  String str = customer.getBillCode().split("_")[0];
		        		  if(key.indexOf(str)!=-1){
		        			  Customer split = map.get(key);
		        			  split.setSh(sh);
		        		  }
		        	  }
		        	  //保存到temp.db中
		        	  FpUtil.writeDataTemp(map);
		        	  tv_customer.refresh();
		});
		
		
		
		//显示有效时间
		Decoder decoder = Base64.getDecoder();
		String[] code = PropertyUtil.getKeyValue("code").split("=");
		String enddate = code[0]+'=';
		try {
			enddate = new String(decoder.decode(enddate), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		date.setText("有效期至："+enddate);
		skr.setText(PropertyUtil.getKeyValue("skr"));
		fhr.setText(PropertyUtil.getKeyValue("fhr"));
		
		BigDecimal sumAmountTemp = new BigDecimal(0.00).setScale(2);
		BigDecimal sumDiscountTemp = new BigDecimal(0.00).setScale(2);
		sumAmount.setText(sumAmountTemp.toString());
		sumDiscount.setText(sumDiscountTemp.toString());
		
		tv_customer.setOnMouseClicked(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent event) {
				if(event.getButton().equals(MouseButton.PRIMARY)    
                        && event.getClickCount() == 2 ){
					Customer cus = tv_customer.getSelectionModel().getSelectedItem();
					if(cus != null){
						configGoodTable(cus);
					}
				}
			}
		});
		limit.setText(PropertyUtil.getKeyValue("limit"));
		List<Customer> cusList = FpUtil.readDataTemp();
		for (Customer customer : cusList) {
			map.put(customer.getBillCode(), customer);
		}
		userList.addAll(cusList);
		configCustomerTable(cusList);
	}

}
